package com.ebo.learn_demo

import org.junit.Test

/**
 * @author zmp
 * @date : 2021/12/21 19:51
 * des:TODO
 */
class ThreadDemo {
    @Test
    fun test() {
        //TODO    Thread.interrupt()
        //TODO    InterruptedException后 Thread.isInterrupted()
//        Thread().isInterrupted
        println(Thread.currentThread().name)

        val a = Object()
        val thread = object : Thread() {
            override fun run() {
                println(name)
                println("thread  isInterrupted:$isInterrupted")
                sleep(10)
                while (!isInterrupted) {
                    synchronized(a) {
                        try {
                            println("thread synchronized   a.wait()")
                            a.wait()
                            println("thread synchronized   a.wait()  =====")
                        } catch (e: Exception) {
                            e.printStackTrace()
                            println("thread Exception  isInterrupted:$isInterrupted")
                            interrupt()
                        } finally {
                            println("thread finally  isInterrupted:$isInterrupted")
                        }
                    }
                }
                println("thread  end isInterrupted:$isInterrupted")
            }
        }

        val thread2 = object : Thread() {
            override fun run() {
                println(name)
                println("thread2  isInterrupted:$isInterrupted")
                while (!isInterrupted) {
                    synchronized(a) {
                        try {
                            println("thread2 synchronized  wait")
                            a.wait()
                            println("thread2 synchronized   wait  =====")
                        } catch (e: Exception) {
                            e.printStackTrace()
                            println("thread2 Exception  isInterrupted:$isInterrupted")
                            interrupt()
                        } finally {
                            println("thread2 finally  isInterrupted:$isInterrupted")
                        }
                    }
                }
                println("thread2  end isInterrupted:$isInterrupted")
            }
        }


        thread.start()
        thread2.start()
        Thread.sleep(500)
        thread.interrupt()
        thread2.interrupt()
        Thread.sleep(500)
        println("========== end ========")
    }
}